<!--
  图片上传组件，同一个页面使用多个该组件时需要确保uploadId值唯一

  用法：
    <f7-picture-upload :params="{type:'avatar',dataKey:'xxxId'}"></f7-picture-upload>
 -->
<template>
    <f7-list class="pic_upload">
        <template v-if="!disabled">
            <span v-for="(file,index) in dbfiles"
                  :key="file.attachmentId"
                  :title="file.fileName">
                <div style="width: 80px;height: 80px;text-align: center;margin: 0 auto;vertical-align: middle;border: 1px solid #b1afaf;border-radius:5px">
                    <img :src="downUrl + '?attachmentId=' + file.attachmentId"
                         @click="openPhotoBrowser(index, file)"/>
                         <a class="col button button-fill color-gray"
                   style="margin-top: -40px;"
                   @click="removeDbFile(file)">删除</a>
                </div>
                <div v-if="file.code" style="font-size: 12px;">{{file.code}}</div>
                
                <div class="gauge demo-gauge"
                     style="top: 10%;position: absolute;padding: 7px;"
                     @click="openPhotoBrowser(index, file)">
                    <!-- <svg width="70px" height="70px" viewBox="0 0 250 250" class="gauge-svg">
            <circle
              stroke="#eeeeee"
              stroke-width="10"
              fill="transparent"
              cx="125"
              cy="125"
              r="120"
              class="gauge-back-circle"
            ></circle>
            <circle
              transform="rotate(-90 125 125)"
              stroke="#2196f3"
              stroke-width="10"
              stroke-dasharray="753.9822368615503"
              stroke-dashoffset="0"
              fill="none"
              cx="125"
              cy="125"
              r="120"
              class="gauge-front-circle"
            ></circle>
            <text
              x="50%"
              y="50%"
              font-weight="500"
              font-size="80"
              fill="#2196f3"
              dy="0"
              text-anchor="middle"
              dominant-baseline="middle"
              class="gauge-value-text"
            >100%</text>
          </svg>-->
                </div>
            </span>
            <span v-for="(file,index) in files"
                  :key="file.id"
                  :title="file.name"
                  v-show="file.active || file.success">
                <div style="width: 80px;height: 80px;text-align: center;margin: 0 auto;vertical-align: middle;border: 1px solid #b1afaf;border-radius:5px">
                    <img v-if="file.thumb"
                         :src="file.thumb"
                         @click="openPhotoBrowser(dbfiles.length + index, file, false)" />
                    <img v-if="!file.thumb"
                         src="../../assets/img/Default_picture.png" />
                         <a v-if="file.success"
                   class="col button button-fill color-gray"
                   style="margin-top: -40px;"
                   @click="removeFile(file)">删除</a>
                <a v-if="file.error"
                   class="col button button-fill color-gray"
                   style="margin-top: -40px;"
                   @click="removeFile(file)">{{formatError(file)}}</a>
                </div>
                <div v-if="file.code" style="font-size: 12px;">{{file.code}}</div>
                <div class="gauge demo-gauge"
                     style="top: 10%;position: absolute;padding: 7px;"
                     v-show="file.active">
                    <svg width="70px"
                         height="70px"
                         viewBox="0 0 250 250"
                         class="gauge-svg">
                        <circle stroke="#eeeeee"
                                stroke-width="10"
                                fill="transparent"
                                cx="125"
                                cy="125"
                                r="120"
                                class="gauge-back-circle" />
                        <circle transform="rotate(-90 125 125)"
                                stroke="#2196f3"
                                stroke-width="10"
                                stroke-dasharray="753.9822368615503"
                                :stroke-dashoffset="(100-file.progress)/100*753.9822368615503"
                                fill="none"
                                cx="125"
                                cy="125"
                                r="120"
                                class="gauge-front-circle" />
                        <text x="50%"
                              y="50%"
                              font-weight="500"
                              font-size="80"
                              fill="#2196f3"
                              dy="0"
                              text-anchor="middle"
                              dominant-baseline="middle"
                              class="gauge-value-text">{{file.progress}}%</text>
                    </svg>
                </div>
            </span>
            <file-upload class="addPic"
                         :input-id="uploadId"
                         :post-action="postUrl"
                         :chunk-enabled="chunkEnabled"
                         :chunk="{
            action: chunkUrl,
            minSize: chunkMinSize * 1048576,
            maxActive: chunkMaxActive,
            maxRetries: chunkMaxRetries,
            finishBody:params,
            handler:handlerClass
          }"
                         :extensions="extensions"
                         :accept="accept"
                         :multiple="multiple"
                         :size="size"
                         v-model="files"
                         @input-filter="inputFilter"
                         @input-file="inputFile"
                         :ref="uploadId"
                         :data="params"
                         v-show="!isPlus"></file-upload>
            <f7-link class="addPic"
                     raised
                     @click="$refs.actionsOneGroup.f7Actions.open()"
                     v-show="isPlus"></f7-link>
        </template>
        <template v-else>
            <span v-for="(file,index) in dbfiles"
                  :key="file.attachmentId">
                <div style="width: 80px;height: 80px;text-align: center;margin: 0 auto;vertical-align: middle;border: 1px solid #b1afaf;border-radius:5px">
                    <img :src="downUrl + '?attachmentId=' + file.attachmentId"
                         @click="openPhotoBrowser(index, file)" />
                </div>
                <div v-if="file.code" style="font-size: 12px;">{{file.code}}</div>
            </span>
        </template>

        <f7-actions ref="actionsOneGroup">
            <f7-actions-group>
                <f7-actions-label>上传方式选择</f7-actions-label>
                <f7-actions-button v-if="!isCode" @click="appendByGallery">手机相册</f7-actions-button>
                <f7-actions-button @click="appendByCamera">相机拍照</f7-actions-button>
                <f7-actions-button color="red">取消</f7-actions-button>
            </f7-actions-group>
        </f7-actions>
    </f7-list>
</template>
<script>
import _ from "lodash";
import ImageCompressor from "image-compressor.js";
import FileUpload from "vue-upload-component";
import formatter from "../framework/formatter";
import Config from "../config";
import ChunkUploadHandler from "../polyfill/ChunkUploadHandler";
export default {
    components: {
        FileUpload,
    },
    props: {
        uploadId: {
            type: String,
            default: "file",
        },
        params: {
            type: Object,
            default: {},
        },
        extensions: {
            type: String,
        },
        accept: {
            type: String,
        },
        multiple: {
            type: Boolean,
            default: true,
        },
        size: {
            type: Number,
            default: 1024 * 1024 * 10,
        },
        chunkUrl: {
            type: String,
            default: "/api/base/chunkUpload/upload",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        // 是否添加时间水印
        timeWatermark: {
            type: Boolean,
            default: false,
        },
        //是否显示二维码编号
        isCode:{
            type: Boolean,
            default: false,
        },
        //二维码数组
        codeList: {
            type: Array,
            default: () => {
                return [];
            },
        },
    },
    data () {
        return {
            downUrl: "/api/base/fileupload/downFile",
            getUrl: "/api/base/fileupload/getFiles",
            deleteUrl: "/api/base/fileupload/delFile",
            postUrl: "/api/base/fileupload/uploadFile",
            files: [],
            dbfiles: [],
            chunkEnabled: true,
            // 1MB by default
            chunkMinSize: 1,
            chunkMaxActive: 3,
            chunkMaxRetries: 5,
            popupOpened: false,
            uploadAuto: true,
            handlerClass: ChunkUploadHandler,
            autoCompress: 2048,
            unwacth: null
        };
    },
    mounted () {
        if (window.plus) {
            this.postUrl = Config.api.upload;
            this.downUrl = Config.api.download;
            // this.deleteUrl = Config.api.deleteUrl;
        }
        // 打包时不需要
        // this.getUrl = Config.api.getUrl;
        // this.deleteUrl = Config.api.deleteUrl;

        // 监听dataKey是否准备完成
        this.unwacth = this.$watch("params", function (val) {
            if (val.dataKey) {
                this.fnInit()
            }
        }, {
            deep: true,
            immediate: true
        })
    },
    created () {
        // 打包时不需要
        // this.getUrl = Config.api.getUrl;
        // this.$f7.request.post(this.getUrl, this.params, (r) => {
        //     r = JSON.parse(r);
        //     if (r && r.success) {
        //         this.dbfiles = r.parameters.files || [];
        //     } else {
        //         this.$framework.$f7.dialog.toast("获取文件失败");
        //     }
        // });
    },
    methods: {
        fnInit () {
            // 取消监听
            this.unwacth && this.unwacth()
            this.$f7.request.post(this.getUrl, this.params, (r) => {
                r = JSON.parse(r);
                if (r && r.success) {
                    this.dbfiles = r.parameters.files || [];
                    if(this.isCode && this.codeList.length > 0){
                        for(var i=0;i<this.dbfiles.length;i++){
                        for(var k=0;k<this.codeList.length;k++){
                            if(this.dbfiles[i].attachmentId == this.codeList[k].attachmentId){
                                this.dbfiles[i].codeId = this.codeList[k].id;
                                this.dbfiles[i].code = this.codeList[k].digtCode;
                            }
                        }
                    }
                    }
                } else {
                    this.$framework.$f7.dialog.toast("获取文件失败");
                }
            });
        },
        getThumb (file) {
            if (file.thumb) {
                return file.thumb;
            } else if (file.name) {
                let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
                if (
                    extension &&
                    "avi,doc,docx,jpg,mp4,pdf,png,ppt,pptx,rar,txt,xls,xlsx,zip"
                        .split(",")
                        .includes(extension.toLowerCase())
                ) {
                    return "/static/img/file/" + extension.toLowerCase() + ".png";
                }
            }
            return "/static/img/file/default.png";
        },
        formatError (file) {
            var error = "上传失败";
            switch (file.error) {
                case "size":
                    error =
                        "上传失败：文件太大，不超过" + formatter.formatFileSize(this.size);
                    break;
                case "extension":
                    error = "上传失败：文件类型不符，只允许" + this.accept;
                    break;
                case "timeout":
                    error = "网络超时";
                    break;
                case "abort":
                    error = "用户放弃";
                    break;
                case "network":
                    error = "网络连接失败";
                    break;
                case "server":
                    error = "服务器错误";
                    break;
                case "denied":
                    error = "请求无效";
                    break;
                default:
                    error = "上传失败";
                    break;
            }
            return error;
        },
        inputFilter (newFile, oldFile, prevent) {
            if (this.isCode) {
                newFile.code = "";
            }
            if (newFile && !oldFile) {
                // Before adding a file
                // 添加文件前
                // Filter system files or hide files
                // 过滤系统文件 和隐藏文件
                if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                    return prevent();
                }
                // Filter php html js file
                // 过滤 php html js 文件
                if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                    return prevent();
                }
                // Automatic compression
                // 自动压缩
                if (
                    !window.plus &&
                    newFile.file &&
                    newFile.type.substr(0, 6) === "image/" &&
                    this.autoCompress &&
                    this.autoCompress > 0 &&
                    this.autoCompress < newFile.size
                ) {
                    newFile.error = "compressing";
                    const imageCompressor = new ImageCompressor(null, {
                        convertSize: Infinity,
                        maxWidth: 512,
                        maxHeight: 512,
                    });
                    imageCompressor
                        .compress(newFile.file)
                        .then((file) => {
                            this.$refs[this.uploadId].update(newFile, {
                                error: "",
                                file,
                                size: file.size,
                                type: file.type,
                            });
                        })
                        .catch((err) => {
                            this.$refs[this.uploadId].update(newFile, {
                                error: err.message || "compress",
                            });
                        });
                }
            }
            if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                // Create a blob field
                // 创建 blob 字段
                newFile.blob = "";
                let URL = window.URL || window.webkitURL;
                if (URL && URL.createObjectURL) {
                    newFile.blob = URL.createObjectURL(newFile.file);
                }
                // Thumbnails
                // 缩略图
                newFile.thumb = "";
                if (newFile.blob && newFile.type.substr(0, 6) === "image/") {
                    newFile.thumb = newFile.blob;
                }
            }
        },
        // add, update, remove File Event
        inputFile (newFile, oldFile) {
            console.log(newFile,"newFile11")
            if (newFile && oldFile) {
                // update
                if (newFile.active && !oldFile.active) {
                    // beforeSend
                    // min size
                    if (
                        newFile.size >= 0 &&
                        this.minSize > 0 &&
                        newFile.size < this.minSize
                    ) {
                        this.$refs[this.uploadId].update(newFile, { error: "size" });
                    }
                }
                if (newFile.progress !== oldFile.progress) {
                    // progress
                }
                if (newFile.error && !oldFile.error) {
                    this.$framework.$f7.dialog.toast(
                        this.formatError(newFile) || "上传失败"
                    );
                }
                
                if (newFile.success && !oldFile.success) {
                    // success
                    let rep = newFile.response;
                    if (Object.keys(rep).includes("success") && rep.success) {
                        if (this.isCode) {
                            console.log(newFile,"newFile")
                        // 上传成功
                        var witnessId = newFile.data.dataKey;
                        var uuid = Math.uuid();
                        var attachmentId = newFile.response.parameters.file.key;
                            this.$f7.request.post('/quality/concreteWitness/bindQrCodeWitness',
                            { attachmentId: attachmentId ,witnessId:witnessId,uuid: uuid},
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    newFile.code = r.parameters.chipdepot.digtCode;
                                    newFile.codeId = r.parameters.chipdepot.id;
                                    this.$emit("success", newFile);
                                } else {
                                    this.$framework.$f7.dialog.toast(r.message || "二维码扫描失败,请删除重新上传");
                                }
                            },
                            (e) => {
                                this.$framework.$f7.dialog.toast("二维码扫描失败,请删除重新上传");
                            }
                            
                        );
                        }else{
                            this.$emit("success", newFile);
                        }
                    } else {
                        // 上传失败
                        this.$f7.dialog.alert(
                            newFile.response.message || "服务器不允许该文件上传"
                        );
                        this.files.pop();
                    }
                }
            }
            if (!newFile && oldFile) {
                // remove
                if (oldFile.success && oldFile.response.id) {
                    // $.ajax({
                    //   type: 'DELETE',
                    //   url: '/upload/delete?id=' + oldFile.response.id,
                    // })
                }
            }
            // Automatically activate upload
            if (
                Boolean(newFile) !== Boolean(oldFile) ||
                oldFile.error !== newFile.error
            ) {
                if (this.uploadAuto && !this.$refs[this.uploadId].active) {
                    this.$refs[this.uploadId].active = true;
                }
            }
        },
        appendByCamera () {
            window.plus.camera.getCamera().captureImage(
                (path) => {
                    if (this.timeWatermark) {
                        this.fnTimeWatermark(path);
                    } else {
                        this.appendToFiles(path);
                    }
                },
                (e) => {
                    if (e.code == 12 || e.code == 11) {
                        this.$framework.$f7.dialog.toast("用户取消选择");
                    } else {
                        this.$framework.$f7.dialog.toast("添加文件失败：" + e.message);
                    }
                    console.log(e);
                }
            );
        },
        // 从相册添加文件
        appendByGallery () {
            window.plus.gallery.pick(
                (path) => {
                    this.appendToFiles(path);
                },
                (e) => {
                    if (e.code == 12 || e.code == 11) {
                        this.$framework.$f7.dialog.toast("用户取消选择");
                    } else {
                        this.$framework.$f7.dialog.toast("添加文件失败：" + e.message);
                    }
                    console.log(e);
                }
            );
        },
        appendToFiles (path, isCompress = true) {
            let self = this;
            function addFile (entry) {
                entry.file((file) => {
                    var reader = new window.plus.io.FileReader();
                    reader.onloadend = (e) => {
                        var file = ((path, name) => {
                            var arr = path.split(","),
                                mime = arr[0].match(/:(.*?);/)[1],
                                bstr = atob(arr[1]),
                                n = bstr.length,
                                u8arr = new Uint8Array(n);
                            while (n--) {
                                u8arr[n] = bstr.charCodeAt(n);
                            }
                            return new File([u8arr], name, { type: mime });
                        })(e.target.result, entry.name);
                        if (self.params) {
                            self.params.sort = (self.params.sort || 0) + 1;
                        }
                        self.$refs[self.uploadId].add(file);                 
                    };
                    reader.readAsDataURL(file);
                });
            }
            window.plus.io.resolveLocalFileSystemURL(
                path,
                (entry) => {
                    if (isCompress) {
                        entry.getMetadata(
                            meta => {
                                if (meta.size > this.autoCompress) {
                                    // 压缩
                                    window.plus.io.getImageInfo({
                                        src: path,
                                        success: info => {
                                            let { width, height } = info;
                                            width > 512 && (width = 512);
                                            height > 512 && (height = 512)
                                            const dst = `_doc/image/${Math.uuid().toLowerCase()}${entry.name}`;

                                            window.plus.zip.compressImage({
                                                src: path,
                                                dst,
                                                width,
                                                height
                                            }, e => {
                                                self.appendToFiles(e.target, false);
                                            }, () => {
                                                console.error("压缩失败！");
                                            })
                                        }
                                    })
                                } else {
                                    // 不压缩
                                    addFile(entry);
                                }
                            },
                            () => {
                                // 获取图片信息失败
                                addFile(entry);
                            }
                        )
                    } else {
                        addFile(entry);
                    }
                },
                (e) => {
                    console.error("appendToFiles error", e);
                }
            );
        },
        // 添加时间水印
        fnTimeWatermark (path) {
            let _this = this,
                image = new Image(),
                canvas = document.createElement("canvas"),
                ctx = canvas.getContext("2d"),
                reader = new window.plus.io.FileReader();

            window.plus.io.resolveLocalFileSystemURL(
                path,
                (entry) => {
                    entry.file((file) => {
                        reader.onload = function () {
                            image.src = reader.result;

                            image.onload = function () {
                                let w = image.naturalWidth,
                                    h = image.naturalHeight;

                                canvas.width = w;
                                canvas.height = h;
                                ctx.drawImage(image, 0, 0);
                                ctx.font = "600 100px serif";
                                ctx.textBaseline = "hanging";
                                let date = formatter.formatDateTime(new Date());
                                ctx.fillStyle = "#FFF";
                                ctx.fillText(date, 20, 100);

                                let arr = canvas.toDataURL("image/png").split(","),
                                    mime = arr[0].match(/:(.*?);/)[1],
                                    bstr = atob(arr[1]),
                                    n = bstr.length,
                                    u8arr = new Uint8Array(n);

                                while (n--) {
                                    u8arr[n] = bstr.charCodeAt(n);
                                }

                                _this.$refs[_this.uploadId].add(
                                    new File([u8arr], file.name, { type: mime })
                                );
                            };
                        };
                        reader.readAsDataURL(file);
                    });
                },
                (e) => {
                    console.log(e);
                }
            );
        },
        removeDbFile (file) {
            let attachmentId = file.attachmentId;
            if (attachmentId != undefined) {
                this.$f7.dialog.confirm("该文件已上传成功，确定要删除嘛？", (r) => {
                    if (r) {
                        this.$f7.request.post(
                            this.deleteUrl,
                            { attachmentId: attachmentId },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    this.dbfiles.splice(this.dbfiles.indexOf(file), 1);
                                    this.$framework.$f7.dialog.toast("文件删除成功");
                                } else {
                                    this.$framework.$f7.dialog.toast(r.message || "文件删除失败");
                                }
                            },
                            (e) => {
                                this.$framework.$f7.dialog.toast("文件删除失败");
                            }
                        );
                        if(!file.codeId){
                            return
                        }
                        //解绑二维码
                        this.$f7.request.post(
                            "/quality/concreteWitness/releaseQrCodeWitness",
                            { id: file.codeId },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    console.log("二维码解绑成功")
                                } else {
                                    console.log(r.message || "二维码解绑失败")
                                }
                            },
                            (e) => {
                                console.log("二维码解绑失败")
                            }
                        );
                    }
                });
            } else {
                this.dbfiles.splice(this.files.indexOf(file), 1);
            }
        },
        removeFile (file) {
            if (
                !file.response.parameters.file ||
                !file.response.parameters.file.key
            ) {
                this.$refs[this.uploadId].remove(file);
                return;
            }
            
            let attachmentId = file.response.parameters.file.key;
            if (file.success || attachmentId != undefined) {
                this.$f7.dialog.confirm("该文件已上传成功，确定要删除嘛？", (r) => {
                    if (r) {
                        this.$f7.request.post(
                            this.deleteUrl,
                            { attachmentId: attachmentId || file.chunk.sessionId },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    if (attachmentId == undefined) {
                                        this.$refs[this.uploadId].remove(file);
                                    } else {
                                        this.files.splice(this.files.indexOf(file), 1);
                                    }
                                    this.$framework.$f7.dialog.toast("文件删除成功");
                                } else {
                                    this.$framework.$f7.dialog.toast(r.message || "文件删除失败");
                                }
                            },
                            (e) => {
                                this.$framework.$f7.dialog.toast("文件删除失败");
                            }
                        );
                        //解绑二维码
                        if(!file.codeId){
                            return
                        }
                        this.$f7.request.post(
                            "/quality/concreteWitness/releaseQrCodeWitness",
                            { id: file.codeId },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    console.log("二维码解绑成功")
                                } else {
                                    console.log(r.message || "二维码解绑失败")
                                }
                            },
                            (e) => {
                                console.log("二维码解绑失败")
                            }
                        );
                    }
                });
            } else {
                this.$refs[this.uploadId].remove(file);
            }
        },
        openPhotoBrowser (index, file, isDb = true) {
            if (window.plus) {
                let
                    filename = 'fileName',
                    downloadurl = 'attachmentId',
                    _file = file

                if (!isDb) {
                    filename = 'name'
                    downloadurl = 'key'
                    _file = file.response.parameters.file


                let params = {
                    filename: _file[filename],
                    downloadurl: _file[downloadurl]
                }

                window.qmSdk.scanFile(params)
                }else{
              let imgname = file.fileName.toLowerCase()
              let params = {
                filename: imgname,
                downloadurl: `${this.downUrl}?attachmentId=${file.attachmentId}`
              }
            console.log(file, params)

            window.qmSdk.scanFile(params)
                }

            } else {
                let photos = [];
                this.dbfiles.forEach((f) => {
                    photos.push({
                        url: this.downUrl + "?attachmentId=" + f.attachmentId,
                        caption: f.fileName,
                    });
                });
                this.files.forEach((f) => {
                    if (f.thumb) {
                        photos.push({
                            url: f.thumb,
                            caption: f.name,
                        });
                    }
                });
                var photoBrowser = this.$f7.photoBrowser.create({
                    photos: photos,
                    type: "popup",
                });
                photoBrowser.open(index || 0);
                photoBrowser.on("closed", () => {
                    photoBrowser.destroy();
                });
            }

        },
        getUploadedCount () {
            return this.files.length + this.dbfiles.length;
        }
    },
    computed: {
        isPlus () {
            return window.plus != undefined;
        },
    },
};
</script>
<style scoped>
.chunk-loading {
    margin: -12px;
    display: flex;
    width: calc(100% + 24px);
}

.chunk-loading .chunk-loading-part {
    height: 25px;
    line-height: 25px;
    flex: 1;
    background: #ccc;
    font-size: 14px;
    color: white;
    text-align: center;
}

.chunk-loading .chunk-loading-part.chunk-loading-part__uploaded {
    background: #28a745;
}

.file-uploads {
    width: 80px;
}

.addPic {
    display: inline-block;
    width: 75px;
    height: 75px;
    border-radius: 3px;
    background: #f8f8f8 url(../../assets/img/img_camera.png) no-repeat center;
    background-size: 50px;
    margin-left: 8px;
    cursor: pointer;
}
</style>

<style lang="less" scoped>
.pic_upload {
    margin: 10px 0;

    > span {
        position: relative;

        > a.button {
            position: absolute;
            bottom: 0;
            width: 100%;
        }
    }
}
</style>
